package test.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by guoyachao on 2018/7/2.
 */
public class CyclicBarrierSimple {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5, () ->
                System.out.println(Thread.currentThread().getName()+"重用")
        );
        for(int i=0;i<5;i++){
            Thread thread = new Thread(new CyclicBarrierWorker(barrier),"Thread"+i);
            thread.start();
        }
    }
    static class CyclicBarrierWorker implements Runnable {
        private CyclicBarrier barrier;
        CyclicBarrierWorker(CyclicBarrier barrier){
            this.barrier = barrier;
        }
        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName()+"-"+i+"CyclicBarrierWorker run");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
